<template>
  <view>
    <u-navbar
      :is-back="false"
      back-icon-color="#f6f6f6"
      title="穿搭发布"
      title-color="#f6f6f6"
      :background="navBackground"
    ></u-navbar>
    <view class="content-box">
      <view class="input-label">选择图片</view>
      <view class="image-box">
        <view v-for="(item, index) in imgList" :key="index">
          <image :src="item" class="image-item"></image>
        </view>
        <view @click="getMoreImg" class="img-add image-item">
          <view class="iconfont icon-more-img"></view>
        </view>
      </view>
      <view>
        <view class="input-label">设置标题</view>
        <u-input
          v-model="title"
          placeholder-style="font-weight:normal;flex-wrap:wrap;width:100%"
          placeholder="请填写你的穿搭标题(最多输入20个字)"
          type="text"
          :border="true"
        />
      </view>
      <view>
        <view class="input-label">穿搭描述</view>
        <u-input
          v-model="contents"
          placeholder-style="font-weight:normal;flex-wrap:wrap;width:100%"
          placeholder="请输入你的穿搭说明(最多输入300个字)"
          type="textarea"
          :border="true"
        />
      </view>
      <view>
        <view class="input-label">穿搭价格</view>
        <u-input
          v-model="price"
          placeholder-style="font-weight:normal;flex-wrap:wrap;width:100%"
          placeholder="请输入衣服或者套装的大致价格(单位:元)"
          type="number"
          :border="true"
        />
      </view>
      <view class="group-picker" @click="showGroupModel()">
        <view class="input-label">选择分组</view>
        <view class="iconfont icon-right-arrow">{{
          groupList[groupIndex].name
        }}</view>
      </view>
      <!--底部按钮-->
      <view class="bottom-box">
        <view @click="saveDraft()">
          <view class="iconfont icon-draft"></view>
          <view style="color: #585858">存草稿</view>
        </view>
        <view style="width: 80%">
          <u-button @click="publish" type="error" :ripple="true" shape="circle"
            >分享穿搭</u-button
          >
        </view>
      </view>
      <view style="color: #cbcfd2;font-size:12px;">{{
        '&ensp;&ensp;&ensp;&ensp;' + priceTips
      }}</view>
      <u-picker
        v-model="showGroup"
        mode="selector"
        :default-selector="[groupIndex]"
        @confirm="groupIndexChange()"
        range-key="name"
        :range="groupList"
      ></u-picker>
    </view>
  </view>
</template>

<script>
let app = getApp();
export default {
  data() {
    return {
      navBackground: app.globalData.navBackground,
      imgList: [],
      groupList: [
        {
          name: '春季',
          group_id: '4',
        },
        {
          name: '夏季',
          group_id: '5',
        },
        {
          name: '秋季',
          group_id: '6',
        },
        {
          name: '冬季',
          group_id: '7',
        },
      ],
      groupIndex: parseInt((new Date().getMonth() + 1) / 4),
      showGroup: false,
      title: '',
      contents: '',
      price: '',
      priceTips:
        '温馨提示：这里的穿搭如果是一整套穿搭，推荐写整套穿搭的价格，如果是一系列不同颜色或者风格的单件衣服，推荐取里面的平均值，主要是为了方便友友们看看自己的荷包够不够^_^!',
    };
  },
  created() {
    // 监听从裁剪页发布的事件，获得裁剪结果
    uni.$on('ecImageCropper', (path) => {
      uni.uploadFile({
        url: app.globalData.baseUrl + '/image/upload',
        filePath: path,
        name: 'file',
        success: (res) => {
          let result = JSON.parse(res.data);
          if (!result.code && typeof result.code != 'undefined') {
            this.imgList.push(result.image_url);
          } else {
            app.showToast(result.errMsg);
          }
        },
        fail: (err) => {
          app.showToast('图片上传失败~');
          console.log('图片上传失败:', err.errMsg);
        },
      });
    });
  },
  onLoad() {
    //获取草稿
    uni.getStorage({
      key: 'draft',
      success: (res) => {
        let result = res.data;
        uni.showModal({
          title: '温馨提示',
          content: '检测到你有穿搭草稿内容尚未发布，是否继续编辑？',
          success: (btn) => {
            if (btn.confirm) {
              this.title = result.title;
              this.contents = result.contents;
              this.imgList = result.imgList;
              this.price = result.price;
              this.groupIndex = result.groupIndex;
            }
          },
        });
      },
    });
  },
  methods: {
    groupIndexChange(data) {
      this.groupIndex = data[0];
    },
    showGroupModel() {
      this.showGroup = true;
    },
    getMoreImg() {
      if (this.imgList.length > 9) {
        app.showToast('最多上传9张图片哦~');
        return;
      }
      this.$u.route({
        // 关于此路径，请见下方"注意事项"
        url: 'ecweapp/ec-image-cropper/ec-image-cropper',
        // 内部已设置以下默认参数值，可不传这些参数
        params: {
          // 输出图片宽度，高等于宽，单位px
          destWidth: 350,
          // 裁剪框宽度，高等于宽，单位px
          rectWidth: 350,
          // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
        },
      });
    },
    publish() {
      if (!app.globalData.isLogin) {
        app.showToast('尚未登录，请登陆后重试~');
        return;
      }
      if (!this.imgList.length) {
        app.showToast('至少选择一张图片');
        return;
      }
      if (this.title.length < 6) {
        app.showToast('标题至少为6个字哦~');
        return;
      }
      if (this.contents.length < 10) {
        app.showToast('内容说明至少为10个字哦~');
        return;
      }
      if (!this.price || this.price <= 0) {
        app.showToast('天底下没有免费的穿搭哦~');
        return;
      }
      if (isNaN(this.price)) {
        app.showToast('穿搭价格需要为一个数字哦~');
        return;
      }
      uni.request({
        url: app.globalData.baseUrl + '/cloth/publish',
        method: 'POST',
        data: {
          cloth_name: this.title,
          cloth_introduce: this.contents,
          cloth_img: JSON.stringify(this.imgList),
          cloth_price: this.price,
          auth_id: app.globalData.user_id,
          group_id: this.groupList[this.groupIndex].group_id,
        },
        success: (res) => {
          let result = res.data;
          if (result.code == 101) {
            app.showToast('发布成功~', 'success');
            uni.clearStorage({
              key: 'draft',
            });
          } else {
            app.showToast(res.data.msg);
          }
          //重置数据
          this.imgList = [];
          this.title = '';
          this.contents = '';
          this.price = 0;
          this.groupIndex = 0;
        },
        fail: (err) => {
          app.showToast('服务器错误，请稍后再试~');
          console.log('上传失败', err.errMsg);
        },
      });
    },
    saveDraft() {
      let draft = new Object();
      draft.title = this.title;
      draft.contents = this.contents;
      draft.imgList = this.imgList;
      draft.price = this.price;
      draft.groupIndex = this.groupIndex;
      uni.setStorage({
        key: 'draft',
        data: draft,
        success: (res) => {
          app.showToast('保存成功', 'success');
        },
        fail: (err) => {
          app.showToast('保存失败');
          console.log(err);
        },
      });
    },
  },
};
</script>

<style>
.content-box {
  width: 90%;
  margin: 0px auto;
}

.content-box > view {
  margin-top: 30rpx;
}

.image-box {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.image-item {
  width: 200rpx;
  height: 200rpx;
  border-radius: 20rpx;
  margin-left: 20rpx;
}

.img-add {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 4rpx #f1eaf8 solid;
}

.input-label {
  font-size: 24rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.bottom-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: center;
  margin-top: 80rpx;
}

.icon-draft {
  font-size: 60rpx;
}
.group-picker {
  display: flex;
  justify-content: space-between;
}
</style>
